package com.asterisk;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import org.asteriskjava.fastagi.AgiChannel;
import org.asteriskjava.fastagi.AgiException;
import org.asteriskjava.fastagi.AgiRequest;
import org.asteriskjava.fastagi.BaseAgiScript;
import org.asteriskjava.fastagi.command.GetVariableCommand;

import com.protocols.GeneralProtocolData;
import com.protocols.sctp.m3ua.sccp.tcap.TcapHandlerInterface;
import com.protocols.sctp.m3ua.sccp.tcap.camel.CamelConnect;
import com.protocols.sctp.m3ua.sccp.tcap.camel.CamelHandlerInterface;
import com.protocols.sctp.m3ua.sccp.tcap.camel.CamelReleaseCall;



public class CallConectorAgiScript extends BaseAgiScript
{   
	public void service(AgiRequest request, AgiChannel channel)throws AgiException
    {
		
		try{
			String CallingNumber=request.getCallerIdNumber();
			String CalledNumber=request.getExtension();
			String channelno = request.getChannel();
			
			CamelHandlerInterface camelhandler;
		
			
			Registry registry=LocateRegistry.getRegistry(9001);	
			camelhandler=(CamelHandlerInterface)(registry.lookup("CamelHandler"));
						
			GeneralProtocolData response=camelhandler.startInitialDP(request.getChannel(), CallingNumber, CalledNumber);
			
			System.out.println("Response Received:"+response.getClass().getName());
			
			String responseType=response.getClass().getSimpleName();
			
			if (responseType.equals("CamelContinue")){
				
				if(CalledNumber.matches("072\\d{7}") || CalledNumber.matches("9472\\d{7}") || CalledNumber.matches("72\\d{7}") ||CalledNumber.matches("+9472\\d{7}") ){
					this.exec("Dial", "Local/9472"+CalledNumber.substring(CalledNumber.length()-7)+"@from-internal");
				}
				else
					this.exec("Dial", "Local/"+CalledNumber+"@from-internal");
				
			}
			else if (responseType.equals("CamelConnect")){
				CamelConnect connect= (CamelConnect)response;
				CalledNumber = connect.getDestinationNumber();
				
				if(CalledNumber.matches("072\\d{7}") || CalledNumber.matches("9472\\d{7}") || CalledNumber.matches("72\\d{7}") ||CalledNumber.matches("+9472\\d{7}") ){
					this.exec("Dial", "Local/9472"+CalledNumber.substring(CalledNumber.length()-7)+"@from-internal");
				}
				else
					this.exec("Dial", "Local/"+CalledNumber+"@from-internal");
				
				
			}
			else 
				hangup();
				
	
			
	        
		}catch(Exception e){
			
		}
    }
}